// 操作共享变量会有问题的售票系统代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <pthread.h>
#include "lock.hpp"
using namespace MyMutex;

class mutexData
{
public:
    mutexData(MyMutex::mutex &lock, const std::string &name)
        : _lock(&lock), _name(name)
    {}
    ~mutexData() {}
    MyMutex::mutex *_lock;
    std::string _name;
};

int ticket = 1000;

void *route(void *arg)
{
    mutexData* md = static_cast<mutexData*>(arg);
    while (1)
    {
        // 加锁
        //md->_lock->lock();
        mutexguard lock(*md->_lock);
        if (ticket > 0) // 1. 判断
        {
            usleep(1000);                               // 模拟抢票花的时间
            printf("%s sells ticket:%d\n", md->_name.c_str(), ticket); // 2. 抢到了票
            ticket--;                                   // 3. 票数--
            // 解锁
            //md->_lock->unlock();
        }
        else
        {
            //md->_lock->unlock();
            break;
        }
        usleep(123);
    }
    return nullptr;
}

int main(void)
{
    // 创建锁
    MyMutex::mutex lock;
    pthread_t t1, t2, t3, t4;

    mutexData *d1 = new mutexData(lock, "thread-1");
    pthread_create(&t1, nullptr, route, d1);

    mutexData *d2 = new mutexData(lock, "thread-2");
    pthread_create(&t2, nullptr, route, d2);

    mutexData *d3 = new mutexData(lock, "thread-3");
    pthread_create(&t3, nullptr, route, d3);

    mutexData *d4 = new mutexData(lock, "thread-4");
    pthread_create(&t4, nullptr, route, d4);

    //    pthread_create(&t1, NULL, route, (void *)"thread 1");
    //    pthread_create(&t2, NULL, route, (void *)"thread 2");
    //    pthread_create(&t3, NULL, route, (void *)"thread 3");
    //    pthread_create(&t4, NULL, route, (void *)"thread 4");
    //
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);

    return 0;
}